<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="clickUpdate(1)">添加员工</el-button>
        </div>
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">员工姓名：</span>
                <el-input placeholder="输入员工姓名" v-model.trim="user_name" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">员工ID：</span>
                <el-input placeholder="输入员工ID" v-model.trim="user_id" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">手机号：</span>
                <el-input placeholder="输入手机号" v-model.trim="tel" oninput="value=value.replace(/[^\d]/g,'')" maxlength="11" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">员工工号：</span>
                <el-input placeholder="输入员工工号" v-model.trim="user_job_no" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">员工状态：</span>
                <el-select v-model="user_type" clearable placeholder="请选择员工状态">
                    <el-option label="正常" value="1" />
                    <el-option label="冻结" value="2" />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">授权类型：</span>
                <el-select v-model="staff_auth" clearable placeholder="请选择授权类型">
                    <el-option label="管理员" value="manager" />
                    <el-option label="站点负责人" value="dc" />
                    <el-option label="质检" value="quality" />
                    <el-option label="放货" value="release" />
                    <el-option label="打包" value="pack" />
                    <el-option label="交货" value="delivery" />
                    <el-option label="客户" value="user" />
                    <el-option label="订单" value="order" />
                </el-select>
            </div>
            <div class="task-one__btn task-wrap-btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column prop="staff_id" label="ID" width="100"></el-table-column>
            <el-table-column prop="job_number" label="工号" width="110"></el-table-column>
            <el-table-column label="员工信息" min-width="256">
                <template #default="{ row }">
                    <div class="table-lr">
                        <el-image class="table-lr__img img-round" loading="lazy" :src="proxy.imgUrl + row.face + '!img_400'" fit="cover" v-if="row.face" />
                        <div class="table-lr__right" :style="{ marginLeft: row.face ? '10px' : '0' }">
                            <p class="lr-title line-one">{{ row.name || "-" }}</p>
                            <p class="lr-user">账号(手机号)：{{ row.mobile }}</p>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="角色权限" min-width="300">
                <template #default="{ row }">
                    <div>
                        <span v-if="row.is_manager == 1">管理员，</span>
                        <span v-if="row.have_quality == 1">质检，</span>
                        <span v-if="row.have_release == 1">放货，</span>
                        <span v-if="row.have_pack == 1">打包，</span>
                        <span v-if="row.have_delivery == 1">交货，</span>
                        <span v-if="row.have_user == 1">客户查看，</span>
                        <span v-if="row.have_order == 1">订单查看，</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="站点负责人" min-width="100">
                <template #default="{ row }">
                    <span>{{ row.have_dc == 0 ? "没有" : "有" }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" min-width="90">
                <template #default="{ row }">
                    <span style="color: #4b93fa">{{ row.status == 0 ? "正常" : "冻结" }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="updated_at_label" label="更新时间" width="160"></el-table-column>
            <el-table-column label="操作" width="180" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickUpdate(2, row)">编辑</el-button>
                    <el-button link type="primary" class="theme-btn" @click="clickFrozen(row)">
                        {{ row.status == 1 ? "解冻" : "冻结" }}
                    </el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
    </div>

    <!-- 添加/编辑 -->
    <el-dialog
        v-model="dialogClass"
        :title="class_type == 1 ? '添加员工' : '编辑员工'"
        width="720px"
        :append-to-body="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        @close="closeClass"
    >
        <el-form ref="ruleClassRef" :model="ruleClassForm" :rules="ruleCheckClass" label-width="140px">
            <el-form-item label="员工工号" prop="job_no">
                <el-input v-model.trim="ruleClassForm.job_no" clearable placeholder="请输入员工工号" />
            </el-form-item>
            <el-form-item label="员工姓名" prop="name">
                <el-input v-model.trim="ruleClassForm.name" clearable placeholder="请输入员工姓名" />
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
                <el-input
                    placeholder="请输入员工手机号"
                    v-model.trim="ruleClassForm.mobile"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    maxlength="11"
                    clearable
                ></el-input>
            </el-form-item>
            <el-form-item label="登录密码" prop="pass">
                <el-input v-model.trim="ruleClassForm.pass" show-password clearable placeholder="请输入员工登录密码" />
                <div class="input-tips">编辑时，密码为空则表示不修改密码</div>
            </el-form-item>
            <el-form-item label="角色权限" required>
                <el-form-item label="管理员" label-width="56px" style="margin-right: 20px">
                    <el-switch
                        v-model="ruleClassForm.is_manager"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <el-form-item label="质检" label-width="40px" style="margin-right: 20px">
                    <el-switch
                        v-model="ruleClassForm.have_quality"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <el-form-item label="放货" label-width="40px" style="margin-right: 20px">
                    <el-switch
                        v-model="ruleClassForm.have_release"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <el-form-item label="打包" label-width="40px" style="margin-right: 20px">
                    <el-switch
                        v-model="ruleClassForm.have_pack"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <el-form-item label="交货" label-width="40px" style="margin-right: 20px">
                    <el-switch
                        v-model="ruleClassForm.have_delivery"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <el-form-item label="客户" label-width="40px" style="margin-right: 20px">
                    <el-switch
                        v-model="ruleClassForm.have_user"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <el-form-item label="订单" label-width="40px">
                    <el-switch
                        v-model="ruleClassForm.have_order"
                        width="72px"
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="开启"
                        inactive-text="关闭"
                    />
                </el-form-item>
                <div class="input-tips">以上角色权限至少开启一种，可以开启多个权限</div>
            </el-form-item>
            <el-form-item label="站点负责人" prop="site_people" required>
                <el-switch
                    v-model="ruleClassForm.site_people"
                    width="72px"
                    size="large"
                    :active-value="1"
                    :inactive-value="0"
                    inline-prompt
                    active-text="有"
                    inactive-text="没有"
                />
                <div class="input-tips">有站点负责人时，必须选择站点。</div>
            </el-form-item>
            <el-form-item label="选择站点" prop="sites_id" v-if="ruleClassForm.site_people == 1">
                <el-select v-model="ruleClassForm.sites_id" multiple collapse-tags collapse-tags-tooltip clearable placeholder="请选择站点（可多选）">
                    <el-option v-for="item in siteArrs" :key="item.dc_id" :label="item.title" :value="item.dc_id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <div class="flexs" style="margin-top: 20px">
                    <el-button type="primary" :loading="form_loading" @click="submitForm(ruleClassRef)"> 确认 </el-button>
                    <el-button @click="resetForm(ruleClassRef)">重置</el-button>
                </div>
            </el-form-item>
        </el-form>
    </el-dialog>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, watch, onBeforeUnmount } from "vue"
import { Search } from "@element-plus/icons-vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

//清除
onBeforeUnmount(() => {})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        staff_id: user_id.value,
        job_number: user_job_no.value,
        so: user_name.value,
        mobile: tel.value,
        status: user_type.value,
        staff_auth: staff_auth.value,
    }
    getdata("staff/index", params)
}

/**
 * 搜索
 * @param {String} user_name 员工名称
 * @param {String} user_id 员工ID
 * @param {String} tel 手机号
 * @param {String} user_job_no 员工工号
 * @param {String} user_type 员工状态，1是正常，2是黑名单
 * @param {String} staff_auth 授权类型，[manager:管理员,dc:站点负责人,quality:质检,release:放货,pack:打包,delivery:交货,user:客户查看,order:订单查看]
 */
const user_name = ref("")
const user_id = ref("")
const tel = ref("")
const user_job_no = ref("")
const user_type = ref("")
const staff_auth = ref("")
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 添加/编辑
 * @param {Boolean} dialogClass 添加/编辑弹窗状态
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Number} class_type 1是添加，2是编辑
 * @param {Array} ruleClassRef 表单规则
 * @param {Object} ruleClassForm  表单字段
 * @param {Object} ruleCheckClass  表单提示
 * @param {Function} submitForm 提交表单
 * @param {Function} closeClass 关闭弹窗
 */
const dialogClass = ref(false)
const class_type = ref(1)
const form_loading = ref(false)
const ruleClassRef = ref(null)
const ruleClassForm = reactive({
    id: "",
    mobile: "",
    name: "",
    pass: "",
    job_no: "",
    is_manager: 0,
    have_quality: 0,
    have_release: 0,
    have_pack: 0,
    have_user: 0,
    have_order: 0,
    have_delivery: 0,
    site_people: 0,
    sites_id: [],
})
const ruleCheckClass = reactive({
    name: [{ required: true, message: "请输入员工名称", trigger: "blur" }],
    pass: [{ required: true, validator: validPassNone, trigger: "blur" }],
    job_no: [{ required: true, message: "请输入员工工号", trigger: "blur" }],
    mobile: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    // sites_id: [{ required: true, type: 'array', message: "请选择员工站点", trigger: "change" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (
                ruleClassForm.is_manager == 0 &&
                ruleClassForm.have_quality == 0 &&
                ruleClassForm.have_release == 0 &&
                ruleClassForm.have_pack == 0 &&
                ruleClassForm.have_user == 0 &&
                ruleClassForm.have_delivery == 0 &&
                ruleClassForm.have_order == 0
            ) {
                proxy.$message({ message: "至少开启一种角色权限!", type: "warning" })
                return
            }
            if (ruleClassForm.site_people == 1 && ruleClassForm.sites_id.length == 0) {
                proxy.$message({ message: "请选择站点", type: "warning" })
                return
            }
            form_loading.value = true
            let data = {
                job_number: ruleClassForm.job_no,
                name: ruleClassForm.name,
                mobile: ruleClassForm.mobile,
                password: ruleClassForm.pass,
                is_manager: ruleClassForm.is_manager, // 管理员[0:不是,1:是]
                have_quality: ruleClassForm.have_quality, // 质检
                have_release: ruleClassForm.have_release, // 放货
                have_pack: ruleClassForm.have_pack, // 打包
                have_delivery: ruleClassForm.have_delivery, //交货
                have_user: ruleClassForm.have_user, // 客户查看
                have_order: ruleClassForm.have_order, // 订单查看
                have_dc: ruleClassForm.site_people,
                dc_ids: ruleClassForm.sites_id,
            }
            if (class_type.value == 2) {
                data.staff_id = ruleClassForm.id
            }
            let url = class_type.value == 1 ? "staff/add" : "staff/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogClass.value = false
                        proxy.$message({ message: `${class_type.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeClass = () => {
    dialogClass.value = false
    resetForm(ruleClassRef.value)
}
const clickUpdate = (type, row) => {
    class_type.value = type
    dialogClass.value = true
    getSite()
    if (type == 2) {
        getSelectSite(row.staff_id)
        setTimeout(() => {
            ruleClassForm.id = row.staff_id
            ruleClassForm.mobile = row.mobile
            ruleClassForm.name = row.name
            ruleClassForm.job_no = row.job_number
            ruleClassForm.site_people = Number(row.have_dc)
            ruleClassForm.is_manager = Number(row.is_manager)
            ruleClassForm.have_quality = Number(row.have_quality)
            ruleClassForm.have_release = Number(row.have_release)
            ruleClassForm.have_pack = Number(row.have_pack)
            ruleClassForm.have_user = Number(row.have_user)
            ruleClassForm.have_order = Number(row.have_order)
            ruleClassForm.have_delivery = Number(row.have_delivery)
        }, 50)
    }
}
// 自定义添加/编辑时密码验证
function validPassNone(rule, value, callback) {
    if (value == "" && class_type.value == 1) {
        callback(new Error("请输入登录密码"))
    } else {
        callback()
    }
}

// 添加时获取站点信息
const siteArrs = ref([])
function getSite() {
    proxy.$axios
        .get("staff/add")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                siteArrs.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 编辑时获取选中站点
function getSelectSite(staff_id) {
    proxy.$axios
        .get("staff/update", {
            params: {
                staff_id,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                let ids = result
                    .filter((item) => item.selected == 1)
                    .map((sub) => {
                        return sub.dc_id
                    })
                ruleClassForm.sites_id = ids
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 冻结/解冻
const clickFrozen = (row) => {
    proxy.$axios
        .post("staff/status", {
            staff_id: row.staff_id,
            status: row.status == 1 ? 0 : 1,
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: "设置成功", type: "success" })
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 删除单个
const clickDel = (row) => {
    postDel(row.staff_id)
}
// 删除接口
function postDel(params) {
    proxy.$axios
        .post("staff/delete", {
            staff_id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "StaffManage",
}
</script>

<style lang="less" scoped>
.table-lr {
    .table-lr__img {
        width: 40px;
        height: 40px;
    }

    .table-lr__right {
        min-height: 40px;
    }
}
</style>
